import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
// import type { loginFormData, loginResponseData } from '@/api/user/type'
//引入用户仓库的类型
import type { UserState } from '@/stores/modules/types/type'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import { constantRouter } from '@/router/router'
const useUserStore = defineStore('User', {
  state(): UserState {
    return {
      token: GET_TOKEN(),
      menuRouter: constantRouter,
      username: '',
      avatar: '',
    }
  },
  actions: {
    async userLogin(loginForm: any) {
      const result: any = await reqLogin(loginForm)
      //如果登录成功
      if (result.code === 20000) {
        this.token = result.data.token
        //本地存储token
        SET_TOKEN(result.data.token)
        //返回一个成功的romise对象
        window.location.reload()
        return 'ok'
      } else {
        //如果登录失败
        return Promise.reject(new Error(result.data))
      }
    },
    async userInfo() {
      const result = await reqUserInfo()
      //如果登录成功获取用户信息
      if (result.code == 20000) {
        this.username = result.data.name
        this.avatar = result.data.avatar
        //登录成功，获取用户信息成功的promise对象
        return 'ok'
      } else {
        //登录失败，获取用户信息失败，
        return Promise.reject(result.message)
      }
    },
    async logoOut() {
      //通知服务器，用户唯一标识失效，但目前没有mock接口
      const result = await reqLogout()
      if (result.code == 20000) {
        this.token = ''
        this.username = ''
        REMOVE_TOKEN()
        window.location.reload()
        return 'ok'
      } else {
        Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
})
export default useUserStore
